import sys
import os
sys.path.append(os.path.join(os.path.dirname(__file__), '..'))

import math

import zxml

def get_samples_by_lables(props, labels, choices):
    (subprops, sublabels) = ([], [])

    for i in range(len(labels)):
        if labels[i] in choices:
            subprops.append(props[i])
            sublabels.append(labels[i])
    return subprops, sublabels

def split_train_test_samples(props, labels, ratio):
    '''将数据按照labels的比例分为训练集和测试集
    Parameters
    ----------
    ratio: float
        测试集所占的比例

    Returns
    -------
    train_samples: [props, labels]
        训练的样本数据
    test_samples: [props, labels]
        用于测试的样本数据
    '''
    
    freq_train = zxml.frequency(labels)
    for key in freq_train:
        freq_train[key] = math.ceil(freq_train[key]*(1-ratio))

    freq_train_curr = { key:0 for key in freq_train }
    (props_test, labels_test, props_train, labels_train) = ([], [], [], [])
    for i in range(len(labels)):
        if freq_train_curr[labels[i]] < freq_train[labels[i]]:
            props_train.append(props[i])
            labels_train.append(labels[i])
            freq_train_curr[labels[i]] += 1
        else:
            props_test.append(props[i])
            labels_test.append(labels[i])

    return [props_train, labels_train], [props_test, labels_test]

    

def test_classifier(classifer, params, train_samples, test_samples):
    import datetime
    spenttime = [0, 0, 0]

    starttime = datetime.datetime.now()
    classifer.train(train_samples[0], train_samples[1], params)
    spenttime[1] = (datetime.datetime.now() - starttime).microseconds
    
    result = classifer.classify(test_samples[0])
    spenttime[0] = (datetime.datetime.now() - starttime).microseconds
    spenttime[2] = spenttime[0] - spenttime[1]

    err = 0
    for i in range(len(result)):
        if result[i] != test_samples[1][i]:
            err += 1

    return (len(train_samples[1]), len(test_samples[1]), err, spenttime)




def print_test_result(msg, result):
    output = "%s:\n" % (msg) + \
             "  数据: (train, test) = (%d, %d)\n" %(result[0], result[1]) + \
             "  错误率: (error, rate) = (%d, %f)\n" % (result[2], result[2]*1.0 / result[1]) + \
             "  time: (all, train, classify) = (%d, %d, %d)" % (result[3][0], result[3][1], result[3][2])

    print(output)
